<template>
  <div class="create-product">
    <div class="header">
      <span class="back" @click="goBack"><i class="iconfont icon-fanhui" style="font-size: 24px;"></i></span>
      创建产品
    </div>
    <div class="container-wrap">
      <div class="container">
        <el-steps direction="vertical" :active="activeStep" finish-status="success">
          <el-step title="请选择你想创建的产品">
            <template #title>
              <span>{{ activeStep === 0 ? '请选择你想创建的产品' : '已选择品类' }}</span>
              <span
                v-if="activeStep"
                class="reselect"
                @click="handleReselect(0)">重新选择</span>
            </template>
            <template #description>
              <div v-if="activeStep === 0">
                <div class="big-type">
                  <div class="type-title">标准类目</div>
                  <ul class="big-type-list">
                    <li
                      v-for="(item, index) in productType"
                      :key="index"
                      :class="[{ 'selected': item.standardCategory === selectedBigType }]"
                      @click="selectProductBigType(item.standardCategory)">
                      {{
                        item.standardCategory }}</li>
                  </ul>
                </div>
                <div class="small-type">
                  <div
                    v-for="(item, index) in productSmallType"
                    :key="index"
                    :title="item.category">
                    <div class="small-type-title">{{ item.category }}</div>
                    <ul class="small-type-list">
                      <li
                        v-for="(li, i) in item.secondClassification"
                        :key="i"
                        :title="li.name"
                        @click="selectProductSmallType(item.category, li.name)">
                        <img :src="li.icon" alt="">
                        <span>{{ li.name }}</span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
              <div v-if="activeStep === 1" class="selected-product-type">
                <img :src="selectedProductType.icon" alt="">
                <span>{{ selectedProductType.name }}</span>
              </div>
            </template>
          </el-step>
          <el-step title="完善产品信息">
            <template #description>
              <div v-if="activeStep === 1" class="device-type">
                <div class="communicate-title"><span class="must">*</span>设备类型：</div>
                <ul>
                  <li
                    v-for="(item, index) in deviceTypeData"
                    :key="index"
                    :class="[{ 'selected': index === selectedDeviceTypeIndex }]"
                    @click="selectedDeviceType(index, item)">{{ deviceTypeMap[item] }}</li>
                </ul>
              </div>
              <div
                v-if="activeStep === 1"
                class="device-type">
                <div class="communicate-title"><span class="must">*</span>通讯协议：</div>
                <ul>
                  <li
                    v-for="(item, index) in communicationProtocolData"
                    :key="index"
                    :class="[{ 'selected': index === selectedCommunicationTypeIndex }]"
                    @click="selectedCommunicationType(index, item)">{{
                      item }}</li>
                </ul>
              </div>
              <div v-if="activeStep === 1" class="communicate-box">
                <div
                  class="not-selected">
                  <div class="dms">
                    <div class="communicate-title"><span class="must">*</span>配网方式：</div>
                    <ul>
                      <li
                        v-for="(item, index) in dmsMethods"
                        :key="index"
                        :class="[{ 'selected': index === selectedDmsIndex }]"
                        @click="selectedDmsMethods(index, item)">{{
                          item }}</li>
                    </ul>
                  </div>
                </div>
              </div>
              <div v-if="activeStep === 1" class="product-info">
                <el-form ref="form" :model="formInfo" :rules="rules" label-width="80px" label-position="right">
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="客户名称" prop="customerCode" class="custom-form-item">
                        <el-select v-model="formInfo.customerCode" placeholder="请选择客户" clearable>
                          <el-option
                            v-for="item in customerData"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="产品图片" prop="icon" class="form-item-img">
                        <div class="product-img">
                          <el-upload
                            class="upload-img"
                            action="/admin/sys-file/upload"
                            :headers="headers"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            :on-error="uploadError"
                            :before-upload="beforeUpload">
                            <img v-if="formInfo.icon" :src="uploadUrl || formInfo.icon" class="uploaded-img">
                            <div v-else>
                              <i class="iconfont icon-shangchuantupian"></i>
                              <div class="text">点击上传</div>
                            </div>
                          </el-upload>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="产品名称" prop="name" class="custom-form-item">
                        <el-input
                          v-model="formInfo.name"
                          placeholder="品牌+产品名，将在用户App界面上显示"
                          maxlength="64"
                          show-word-limit
                          clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="产品型号" prop="productModel" class="custom-form-item">
                        <el-input
                          v-model="formInfo.productModel"
                          placeholder="请输入您的产品型号，多个以;隔开"
                          maxlength="64"
                          show-word-limit
                          clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="产品说明" prop="description" class="custom-form-item">
                        <el-input
                          v-model="formInfo.description"
                          type="textarea"
                          placeholder="请输入产品说明，尽可能描述清楚产品型号"
                          clearable
                          maxlength="200"
                          show-word-limit
                          :rows="4"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
    </div>
    <div class="btn"><el-button type="primary" size="14" :disabled="!isDisabled" @click="onSubmit">创建产品</el-button>
    </div>
  </div>
</template>
<script>
import { customer, scheme, createProduct, deviceCategories } from '@/api/product/create-product'
import store from '@/store'
export default {
  name: 'createProduct',
  data() {
    return {
      activeStep: 0, // 正在进行中的步骤
      productType: {}, // 产品类型
      communicationProtocolData: [], // 通讯协议数据
      deviceTypeData: [], // 设备类型数据
      deviceTypeMap: {
        'gateway': '网关设备',
        'childrenDevice': '网关子设备',
        'device': '普通设备'
      },
      dmsMethods: [], // 配网方式
      selectedBigType: null, // 默认选中的产品大类
      productSmallType: [], // 产品小类
      selectedProductType: {}, // 已选择的产品类型
      selectedDeviceTypeIndex: null, // 选中设备类型
      selectedCommunicationTypeIndex: null, // 选中通讯类型
      selectedNetworkIndex: null, // 选中联网方式索引
      selectedDmsIndex: null, // 选中配网方式索引
      customerData: [], // 客户信息
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      formInfo: { // 产品信息
        customerCode: '', // 选中的客户名称
        name: '', // 产品名称
        productModel: '', // 产品型号
        description: '', // 产品说明
        deviceType: '', // 设备类型
        communicationProtocol: '', // 通讯协议
        networkDistributeMode: '', // 选中配网方式
        icon: '' // 产品icon
      },
      uploadUrl: '', // 上传的图片地址
      rules: {
        customerCode: [
          { required: true, message: '请选择客户', trigger: 'change' },
          {},
          { validator: this.validateCustomer, trigger: 'change' }
        ],
        icon: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productModel: [
          { required: true, message: '请输入产品型号', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入产品说明', trigger: 'blur' }
        ]
      },
      radioValue: 1
    }
  },
  computed: {
    isDisabled() {
      return this.activeStep === 1 && this.formInfo.customerCode !== '' && this.formInfo.name && this.formInfo.productModel && this.formInfo.description && this.formInfo.deviceType && this.formInfo.communicationProtocol && this.formInfo.networkDistributeMode && this.formInfo.icon
    }
  },
  watch: {
    selectedDeviceTypeIndex(newVal, oldVal) {
      this.checkValues()
    },
    selectedCommunicationTypeIndex(newVal, oldVal) {
      this.checkValues()
    },
    selectedNetworkIndex(newVal, oldVal) {
      this.checkValues()
    },
    selectedDmsIndex(newVal, oldVal) {
      this.checkValues()
    }
  },
  created() {
    this.queryCategory()
    this.queryCustomer()
    this.queryScheme()
  },
  methods: {
    // 客户名称校验提示
    validateCustomer(rule, value, callback) {
      if (value === '') {
        callback(new Error('请选择客户名称'))
      } else {
        callback()
      }
    },
    // 查询产品品类
    queryCategory() {
      deviceCategories().then(res => {
        this.productType = res.data.data.categories
        this.selectedBigType = res.data.data.categories[0].standardCategory
        this.filterProductSmallType()
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 获取客户信息
    queryCustomer() {
      customer().then(res => {
        this.customerData = res.data.data.records
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 获取联网方式和配网方式
    queryScheme() {
      scheme().then(res => {
        this.deviceTypeData = res.data.data.deviceType
        this.communicationProtocolData = res.data.data.communicationProtocol
        // this.networkMethods = res.data.data.networkMode
        this.dmsMethods = res.data.data.networkDistributeMode
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },
    /**
     * 创建产品
     * @param categoryCode 产品类型code
     * @param icon 产品icon
     * @param customerCode 客户code
     * @param name 产品名称
     * @param productModel 产品型号
     * @param description 产品说明
     * @param networkMode 联网方式
     * @param networkDistributeMode 配网方式
     */
    onSubmit() {
      const params = {
        categoryCode: this.selectedProductType.categoryCode,
        icon: this.selectedProductType.icon,
        ...this.formInfo
      }
      createProduct(params).then(res => {
        this.$message.success('创建成功')
        this.$router.push({
          path: '/product/product-details/index',
          query: {
            productId: res.data.data.productId,
            developStatus: 0,
            productName: res.data.data.name
          }
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 选择产品大类
    selectProductBigType(value) {
      this.selectedBigType = value
      this.filterProductSmallType()
    },
    // 把产品小类数据过滤出来
    filterProductSmallType() {
      // 通过产品大类code过滤产品小类
      this.productSmallType = this.productType.find(item => item.standardCategory === this.selectedBigType).primaryClassification
    },
    // 选择产品小类
    selectProductSmallType(category, name) {
      // 遍历 productSmallType 数组
      for (const item of this.productSmallType) {
        if (item.category === category) {
          // 遍历 secondClassification 数组
          for (const li of item.secondClassification) {
            if (li.name === name) {
              // 检查 addProcess 数组是否存在且有元素
              this.selectedProductType = li
            }
          }
        }
      }
      this.activeStep = 1 // 进行到第2步，通讯方案
    },
    // 产品图片上传成功
    handleSuccess(res, file) {
      this.formInfo.icon = res.data.url
      this.uploadUrl = URL.createObjectURL(file.raw)
    },
    // 上传失败
    uploadError(err, file, fileList) {
      this.$message.error(err)
    },
    // 产品图片上传之前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // 校验图片格式是否为png
        const isPng = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg'
        if (!isPng) {
          this.$message.error('只能上传png/jpg/jpeg格式的图片')
          return
        }
        // 使用FileReader获取图片尺寸
        const reader = new FileReader()
        reader.onload = (e) => {
          const image = new Image()
          image.onload = () => {
            // 校验图片大小是否小于100M
            if (file.size <= 100 * 1024 * 1024) {
              resolve(file)
            } else {
              this.$message.error('图片大小不能超过100M')
            }
          }
          image.src = e.target.result
        }
        reader.readAsDataURL(file)
      })
    },
    // 重新选择
    handleReselect(step) {
      this.formInfo.customerCode = ''
      this.formInfo.name = ''
      this.formInfo.productModel = ''
      this.formInfo.description = ''
      this.formInfo.deviceType = ''
      this.formInfo.communicationProtocol = ''
      this.formInfo.networkDistributeMode = ''
      this.formInfo.icon = ''

      if (step === 0) {
        this.selectedProductType = {}
      }
      this.selectedDeviceTypeIndex = null
      this.selectedCommunicationTypeIndex = null
      this.selectedNetworkIndex = null
      this.selectedDmsIndex = null
      this.activeStep = step === 0 ? 0 : 1
    },
    // 选择设备类型
    selectedDeviceType(index, item) {
      this.selectedDeviceTypeIndex = index
      this.formInfo.deviceType = item
    },
    // 选择通讯协议
    selectedCommunicationType(index, item) {
      this.selectedCommunicationTypeIndex = index
      this.formInfo.communicationProtocol = item
      if (item === '虚拟设备') {
        this.selectedNetworkIndex = null
        this.selectedDmsIndex = null
        if (this.selectedDeviceTypeIndex !== null) {
          this.activeStep = 2
        }
      }
    },
    // 选择联网方式
    selectedNetworkMethods(index, item) {
      this.selectedNetworkIndex = index
      this.formInfo.networkMode = item
    },
    // 选择配网方式
    selectedDmsMethods(index, item) {
      this.selectedDmsIndex = index
      this.formInfo.networkDistributeMode = item
    },
    checkValues() {
      // 检查两个值是否都为 null
      this.activeStep = (this.selectedCommunicationTypeIndex !== null && this.selectedNetworkIndex !== null && this.selectedDmsIndex !== null && this.selectedDeviceTypeIndex !== null) || (this.communicationProtocolData[this.selectedCommunicationTypeIndex] === '虚拟设备' && this.selectedDeviceTypeIndex !== null) ? 2 : this.activeStep
    }
  }
}
</script>
<style lang="scss" scoped>
.create-product {
  font-size: 14px;
  height: 100%;
  display: flex;
  justify-content: space-between;
  flex-direction: column;

  .header {
    margin-bottom: 31px;
    font-size: 18px;
    font-weight: 600;
    color: #333333;
    display: flex;
    align-items: center;

    .back {
      margin-right: 13px;
      cursor: pointer;
    }
  }

  .container-wrap {
    flex-grow: 1;
  }
  .container {
    margin-left: 16px;
    margin-bottom: 20px;
  }

  .type-title {
    display: inline-block;
    font-weight: 400;
    color: #808080;
    float: left;
    margin-right: 16px;
  }

  .reselect {
    font-weight: 400;
    color: #2B6FF8;
    margin-left: 24px;
    cursor: pointer;
  }

  .big-type {
    color: #353535;
    margin-top: 24px;

    .big-type-list {
      list-style: none;
      display: flex;
      flex-wrap: wrap;
      margin: 0;
      padding: 0;

      li {
        font-weight: 400;
        color: #353535;
        padding: 6px 16px;
        border-radius: 4px;
        border: 1px solid #D7D6D6;
        margin-right: 12px;
        margin-bottom: 16px;
        cursor: pointer;
        box-sizing: border-box;
      }

      li:hover {
        border: 1px solid #275FE8;
      }

      li:last-child {
        margin-right: 0;
      }

      .selected {
        background: #275FE8;
        color: #fff;
        border: none;
      }
    }
  }

  .small-type {
    margin-bottom: 22px;
    margin-top: 16px;
    padding: 10px;
    border: 1px solid #DEDEDE;

    .small-type-title {
      margin: 8px 6px;
    }

    .small-type-list {
      list-style: none;
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin: 4px 0;
      padding: 0;

      li {
        height: 48px;
        line-height: 48px;
        font-weight: 400;
        color: #353535;
        border-radius: 2px;
        border: 1px solid #D7D6D6;
        margin-bottom: 16px;
        cursor: pointer;
        flex-basis: calc(20% - 14px);
        margin: 0 6px 12px 6px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        overflow: hidden;

        span {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        img {
          width: 36px;
          height: 36px;
          margin-left: 8px;
          margin-right: 11px;
        }
      }

      li:last-child {
        margin-right: 0;
      }

      li:hover {
        box-shadow: 2px 2px 6px 0px rgba(0, 0, 0, 0.15);
        border: none;
      }
    }
  }

  .selected-product-type {
    width: 193px;
    height: 48px;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #DEDEDE;
    display: flex;
    align-items: center;
    margin-top: 16px;
    margin-bottom: 32px;

    img {
      width: 36px;
      height: 36px;
      margin-left: 16px;
      margin-right: 11px;
    }
  }

  .fictitious {
    display: flex;
    align-items: center;
    color: #808080;
    margin: 24px 0;

    .communicate-title {
      margin-right: 12px;
    }
  }

  .device-type {
    display: flex;
    align-items: center;
    margin: 24px 0;
    font-weight: 400;
    color: #808080;

    .selected {
      background: #275FE8;
      color: #fff;
    }

    ul {
      list-style: none;
      display: flex;
      padding: 0;
      margin: 0;

      li {
        padding: 6px 18px;
        border-radius: 6px;
        border: 1px solid #DEDEDE;
        margin-left: 14px;
        cursor: pointer;
      }

      li:hover {
        border: 1px solid #275FE8;
      }
    }

    .must {
      color: #F56C6C;
      margin-right: 4px;
    }
  }

  .communicate-box {
    margin-top: 8px;
    margin-bottom: 32px;

    .networking,
    .dms {
      display: flex;
      align-items: center;
      margin: 24px 0;
      font-weight: 400;
      color: #808080;

      .selected {
        background: #275FE8;
        color: #fff;
      }
    }

    ul {
      list-style: none;
      display: flex;
      padding: 0;
      margin: 0;

      li {
        padding: 6px 18px;
        border-radius: 6px;
        border: 1px solid #DEDEDE;
        margin-left: 14px;
        cursor: pointer;
      }

      li:hover {
        border: 1px solid #275FE8;
      }
    }

    .selected-communicate {
      margin-bottom: 24px;
      li {
        margin-left: 0;
        margin-right: 23px;
      }
    }

    .must {
      color: #F56C6C;
      margin-right: 4px;
    }
  }

  .product-info {
    // border-radius: 4px 4px 4px 4px;
    // border: 1px solid #DEDEDE;
    padding: 24px 23px;
    margin-top: 8px;

    .upload-img {
      .uploaded-img {
        width: 80px;
        height: 80px;
      }

      ::v-deep .el-upload {
        width: 80px;
        height: 80px;
        border: 1px dashed #DEDEDE;
        border-radius: 4px;
        font-weight: 400;
        color: #808080;
      }

      .icon-shangchuantupian {
        width: 32px;
        height: 32px;
        font-size: 32px;
        position: absolute;
        top: 11px;
        left: 25px;
      }

      .text {
        margin-top: 40px;
      }
    }
  }

  .btn {
    width: 100%;
    text-align: center;
  }

  .custom-form-item .el-input,
  .custom-form-item .el-select {
    width: 100%;
  }
}

::v-deep .el-input__inner {
  padding-left: 15px;
  padding-right: 50px;
}

::v-deep .el-step.is-vertical .el-step__head {
  width: 22px;
}

::v-deep .el-step__icon {
  width: 22px;
  height: 22px;
  background: #CACFDA;
  color: #fff;
  font-size: 14px;

  .el-step__icon-inner {
    font-weight: 400;
  }

  &.is-text {
    border: none;
  }
}

::v-deep .is-process .el-step__icon {
  background: #275FE8;
  color: #fff;
}

::v-deep .el-step.is-vertical .el-step__line {
  width: 0px;
  background-color: transparent;
  border-left: 1px dotted #CACFDA;
}

::v-deep .el-step__head.is-process {
  .el-step__line {
    border-left: 1px solid #3260CF;
  }
}

::v-deep .el-step__title {
  font-size: 14px;
  font-weight: 600;
  color: #000000;
}

::v-deep .el-step__description {
  font-size: 14px;
  color: #000000;
  padding-right: 0;
}

::v-deep .is-success {
  .el-step__icon {
    background: #fff;
    color: #275FE8;
    border: 1px solid #275FE8;
    border-left: 1px solid #3260CF;
  }

  .el-step__line {
    border-left: 1px solid #3260CF !important;
  }

  .el-step__line-inner {
    height: auto !important;
  }
}

::v-deep .el-textarea .el-input__count {
  background: transparent;
  right: 20px;
  bottom: 0px;
}
</style>
